<template>
    <div>
        <el-card class="filter-card">
            <div class="filter-flex-row-left">
                <el-form :inline="true" :model="queryForm" class="filter-form filter-form-left" size="small">
                    <el-form-item label="栋舍类型">
                        <el-select v-model="queryForm.House_typeId" placeholder="请选择栋舍类型" clearable style="width: 150px">
                            <el-option v-for="item in houseTypeList" :key="item.House_typeId" :label="item.DongsheName"
                                :value="item.House_typeId" />
                            <el-option label="请选择栋舍类型" :value="-1" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="栋舍名称">
                        <el-input v-model="queryForm.House_name" placeholder="请输入栋舍名称" clearable style="width: 150px" />
                    </el-form-item>
                    <el-form-item label="负责人">
                        <el-input v-model="queryForm.Manager" placeholder="请输入负责人姓名" clearable style="width: 150px" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleSearch">查询</el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-button @click="handleReset">重置</el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="danger" @click="showAddDialog = true">新增栋舍</el-button>
                        <el-button type="danger" :disabled="!selectedRows.length" @click="handleBatchDelete">批量删除</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </el-card>
        <!-- 新增弹窗 -->
        <el-dialog v-model="showAddDialog" title="栋舍管理-新增" width="600px" :close-on-click-modal="false">
            <el-form :model="addForm" :rules="addRules" ref="addFormRef" label-width="100px">
                <el-form-item label="栋舍类型" prop="House_typeId" required>
                    <el-select v-model="addForm.House_typeId" placeholder="请选择栋舍类型">
                        <el-option v-for="item in houseTypeList" :key="item.House_typeId" :label="item.DongsheName" :value="item.House_typeId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="栋舍名称" prop="House_name" required>
                    <el-input v-model="addForm.House_name" placeholder="请输入栋舍名称" />
                </el-form-item>
                <el-form-item label="负责人" prop="Manager" required>
                    <el-input v-model="addForm.Manager" placeholder="请输入负责人" />
                </el-form-item>
                <el-form-item>
                    <div style="color:#888;font-size:13px;">注：用于以负责人维度汇总栋舍绩效使用。</div>
                </el-form-item>
                <el-form-item label="生产人员" prop="Producer">
                    <el-input v-model="addForm.Producer" placeholder="请输入生产人员" />
                </el-form-item>
                <el-form-item>
                    <div style="color:#888;font-size:13px;">注：用于移动端查看我管理的栋舍使用。</div>
                </el-form-item>
                <el-form-item label="状态" prop="Status">
                    <el-radio-group v-model="addForm.Status">
                        <el-radio :label="true">启用</el-radio>
                        <el-radio :label="false">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="备注" prop="Remarks">
                    <el-input v-model="addForm.Remarks" type="textarea" placeholder="请输入备注" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="showAddDialog = false">取消</el-button>
                <el-button type="primary" @click="handleAddSubmit">保存</el-button>
            </template>
        </el-dialog>
        <!-- 编辑弹窗 -->
        <el-dialog v-model="showEditDialog" title="栋舍管理-编辑" width="600px" :close-on-click-modal="false">
            <el-form :model="editForm" :rules="addRules" ref="editFormRef" label-width="100px">
                <el-form-item label="栋舍类型" prop="House_typeId" required>
                    <el-select v-model="editForm.House_typeId" placeholder="请选择栋舍类型">
                        <el-option v-for="item in houseTypeList" :key="item.House_typeId" :label="item.DongsheName" :value="item.House_typeId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="栋舍名称" prop="House_name" required>
                    <el-input v-model="editForm.House_name" placeholder="请输入栋舍名称" />
                </el-form-item>
                <el-form-item label="负责人" prop="Manager" required>
                    <el-input v-model="editForm.Manager" placeholder="请输入负责人" />
                </el-form-item>
                <el-form-item>
                    <div style="color:#888;font-size:13px;">注：用于以负责人维度汇总栋舍绩效使用。</div>
                </el-form-item>
                <el-form-item label="生产人员" prop="Producer">
                    <el-input v-model="editForm.Producer" placeholder="请输入生产人员" />
                </el-form-item>
                <el-form-item>
                    <div style="color:#888;font-size:13px;">注：用于移动端查看我管理的栋舍使用。</div>
                </el-form-item>
                <el-form-item label="状态" prop="Status">
                    <el-radio-group v-model="editForm.Status">
                        <el-radio :label="true">启用</el-radio>
                        <el-radio :label="false">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="备注" prop="Remarks">
                    <el-input v-model="editForm.Remarks" type="textarea" placeholder="请输入备注" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="showEditDialog = false">取消</el-button>
                <el-button type="primary" @click="handleEditSubmit">保存</el-button>
            </template>
        </el-dialog>

        <el-table 
            :data="tableData" 
            border 
            style="width: 100%; margin-top: 20px;"
            @selection-change="handleSelectionChange"
            :row-class-name="getRowClassName"
        >
            <el-table-column 
                type="selection" 
                width="55" 
                align="center"
                :selectable="selectable"
            />
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column prop="DongsheName" label="栋舍类型" width="100"/>
            <el-table-column prop="House_name" label="栋舍名称" width="100"/>
            <el-table-column prop="Manager" label="负责人" width="100"/>
            <el-table-column prop="Producer" label="生产人员" width="100"/>
            <el-table-column prop="Status" label="状态">
                <template #default="scope">
                    <el-tag
                        :type="scope.row.Status ? 'success' : 'info'"
                        style="cursor: pointer"
                        @click="handleStatusChange(scope.row)"
                    >
                        {{ scope.row.Status ? '启用' : '禁用' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="Creator" label="创建人" />
            <el-table-column prop="Create_time" label="创建时间" width="180">
                <template #default="scope">
                    {{ formatDate(scope.row.Create_time) }}
                </template>
            </el-table-column>
            <el-table-column prop="Modifier" label="修改人" />
            <el-table-column prop="Modify_time" label="修改时间" width="180">
                <template #default="scope">
                    {{ formatDate(scope.row.Modify_time) }}
                </template>
            </el-table-column>
            <el-table-column label="操作" width="250" align="center" header-align="center">
                <template #default="scope">
                    <el-tooltip
                        content="禁用状态下无法操作"
                        placement="top"
                        :disabled="scope.row.Status"
                    >
                        <span>
                            <el-button
                                type="primary"
                                size="small"
                                text
                                @click="onEdit(scope.row)"
                                :disabled="!scope.row.Status"
                            >修改</el-button>
                            <el-button
                                type="danger"
                                size="small"
                                text
                                @click="onDelete(scope.row)"
                                :disabled="!scope.row.Status"
                            >删除</el-button>
                            <el-button
                                type="primary"
                                size="small"
                                text
                                @click="goToColumnManagement(scope.row)"
                                :disabled="!scope.row.Status"
                            >栏位管理</el-button>
                        </span>
                    </el-tooltip>
                </template>
            </el-table-column>




        </el-table>

        <el-pagination style="margin: 20px auto 0 auto; display: flex; justify-content: center;" background :current-page="pageIndex"
            :page-size="pageSize" :total="total" layout="total, prev, pager, next, jumper"
            @current-change="handlePageChange" />
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from 'vue'
import axios from 'axios'
import { Sheep_BreedingRead, Sheep_BreedingWrite } from '@/utils/Interceptors'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router';

const router = useRouter();

interface HouseTypeItem {
    House_typeId: number
    DongsheName: string
    IsDelete: boolean
}

const queryForm = ref({
    House_typeId: -1 as number, // 初始值为 number 类型
    House_name: '',
    Manager: ''
})

const houseTypeList = ref<HouseTypeItem[]>([])
const tableData = ref([])
const total = ref(0)
const pageIndex = ref(1)
const pageSize = ref(20)

// 新增弹窗控制
const showAddDialog = ref(false)
const addFormRef = ref()
const addForm = reactive({
    House_typeId: undefined,
    House_name: '',
    Manager: '',
    Producer: '',
    Remarks: '',
    Status: true,
    Creator: '' // 可根据实际登录用户赋值
})
const addRules = {
    House_typeId: [{ required: true, message: '请选择栋舍类型', trigger: 'change' }],
    House_name: [{ required: true, message: '请输入栋舍名称', trigger: 'blur' }],
    Manager: [{ required: true, message: '请输入负责人', trigger: 'blur' }]
}

const showEditDialog = ref(false)
const editFormRef = ref()
const editForm = reactive({
  BuildingId: 0,
  House_typeId: undefined,
  House_name: '',
  Manager: '',
  Producer: '',
  Status: true,
  Remarks: '',
  Creator: '',
  Create_time: '',
  Modifier: '',
  IsDelete: false
})

function onEdit(row: any) {
  // 反填数据
  Object.assign(editForm, row)
  showEditDialog.value = true
  nextTick(() => {
    editFormRef.value && editFormRef.value.clearValidate()
  })
}

function onDelete(row: any) {
  ElMessageBox.confirm(
    `确定要删除栋舍【${row.House_name}】吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const res = await Sheep_BreedingWrite.delete('/api/Sheepfarm/DeleteBuildingManagement', {
        data: { BuildingId: row.BuildingId }
      })
      if (res.data.code === 200) {
        ElMessage.success('删除成功')
        getTableData()
      } else {
        ElMessage.error(res.data.msg || '删除失败')
      }
    } catch (e) {
      ElMessage.error('网络异常，删除失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

function goToColumnManagement(row: any) {
  router.push({
    path: '/ColumnManagement',
    query: {
      buildingId: row.BuildingId,
      houseTypeName: row.DongsheName
    }
  });
}

const getHouseTypeList = async () => {
    const res = await Sheep_BreedingRead.get('/api/Sheepfarm/SearchHouse_typeInfo')
    if (res.data.code === 200) {
        houseTypeList.value = res.data.data
    }
}

const getTableData = async () => {
    const params = {
        House_typeId: queryForm.value.House_typeId,
        House_name: queryForm.value.House_name,
        Manager: queryForm.value.Manager,
        PageIndex: pageIndex.value,
        PageSize: pageSize.value
    }
    const res = await Sheep_BreedingRead.get('/api/Sheepfarm/SearchBuildingManagement', { params })
    if (res.data.code === 200) {
        tableData.value = res.data.PageData
        total.value = res.data.TotalCount
    }
}

const handleSearch = () => {
    pageIndex.value = 1
    getTableData()
}

const handleReset = () => {
    queryForm.value = { House_typeId: -1, House_name: '', Manager: '' }
    pageIndex.value = 1
    getTableData()
}

const handlePageChange = (val: number) => {
    pageIndex.value = val
    getTableData()
}

// 新增保存
const handleAddSubmit = () => {
    addFormRef.value.validate(async (valid: boolean) => {
        if (!valid) return
        // 这里 Creator 建议用实际登录用户名
        addForm.Creator = '阿浩'
        // 只传接口需要的字段
        const postData = {
            House_typeId: addForm.House_typeId,
            House_name: addForm.House_name,
            Manager: addForm.Manager,
            Producer: addForm.Producer,
            Remarks: addForm.Remarks,
            Creator: addForm.Creator
        }
        try {
            const res = await Sheep_BreedingWrite.post('/api/Sheepfarm/CreateBuildingManagement', postData)
            if (res.data.code === 200) {
                ElMessage.success('新增成功')
                showAddDialog.value = false
                getTableData()
                nextTick(() => {
                    addFormRef.value.resetFields()
                })
            } else {
                ElMessage.error(res.data.msg || '新增失败')
            }
        } catch (e) {
            ElMessage.error('网络异常，新增失败')
        }
    })
}

const handleEditSubmit = () => {
  editFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    // 可根据实际登录用户赋值
    editForm.Modifier = '阿浩'
    try {
      const res = await Sheep_BreedingWrite.put('/api/Sheepfarm/UpdateBuildingManagement', editForm)
      if (res.data.code === 200) {
        ElMessage.success('修改成功')
        showEditDialog.value = false
        getTableData()
      } else {
        ElMessage.error(res.data.msg || '修改失败')
      }
    } catch (e) {
      ElMessage.error('网络异常，修改失败')
    }
  })
}

function formatDate(val: string) {
    if (!val) return ''
    // 兼容 ISO 字符串，去掉毫秒和 T
    return val.replace('T', ' ').replace(/\..*$/, '')
}

interface BuildingRow {
    BuildingId: number;
    House_typeId: number;
    House_name: string;
    Manager: string;
    Producer: string;
    Status: boolean;
    DongsheName: string;
    Creator: string;
    Create_time: string;
    Modifier: string;
    Modify_time: string;
    Remarks: string;
    IsDelete: boolean;
}

const selectedRows = ref<BuildingRow[]>([]);

// 表格多选变化
function handleSelectionChange(selection: BuildingRow[]) {
    // 过滤掉禁用状态的行
    selectedRows.value = selection.filter(row => row.Status);
}

// 添加表格行选择控制方法
function selectable(row: BuildingRow) {
    return row.Status; // 只有启用状态的行可以被选择
}

// 批量删除
async function handleBatchDelete() {
    if (!selectedRows.value.length) {
        ElMessage.warning('请选择要删除的栋舍');
        return;
    }

    try {
        await ElMessageBox.confirm(
            `确定要删除选中的 ${selectedRows.value.length} 个栋舍吗？`,
            '批量删除确认',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        );

        const params = {
            BuildingIds: selectedRows.value.map(row => row.BuildingId)
        };

        const res = await Sheep_BreedingWrite.delete('/api/Sheepfarm/BatchDeleteBuildingManagement', {
            data: params
        });

        if (res.data.code === 200) {
            ElMessage.success('批量删除成功');
            selectedRows.value = [];
            getTableData();
        } else {
            ElMessage.error(res.data.msg || '批量删除失败');
        }
    } catch (err) {
        if (err !== 'cancel') {
            ElMessage.error('操作失败');
        }
    }
}

// 切换启用/禁用状态
async function handleStatusChange(row: BuildingRow) {
    try {
        const newStatus = !row.Status;
        const confirmText = `确定要${newStatus ? '启用' : '禁用'}栋舍"${row.House_name}"吗？`;
        
        await ElMessageBox.confirm(
            confirmText,
            '状态修改确认',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        );

        const params = {
            BuildingId: row.BuildingId,
            Status: newStatus
        };

        const res = await Sheep_BreedingWrite.put('/api/Sheepfarm/UpdateBuildingManagementStatus', params);

        if (res.data.code === 200) {
            ElMessage.success(`${newStatus ? '启用' : '禁用'}成功`);
            getTableData();
        } else {
            ElMessage.error(res.data.msg || '操作失败');
        }
    } catch (err) {
        if (err !== 'cancel') {
            ElMessage.error('操作失败');
        }
    }
}

// 设置行的类名
function getRowClassName({ row }: { row: BuildingRow }) {
    return row.Status ? '' : 'disabled-row';
}

onMounted(() => {
    getHouseTypeList()
    getTableData()
})
</script>

<style scoped>
.filter-card {
    margin-bottom: 20px;
    border-radius: 8px;
    box-shadow: none;
}
.filter-flex-row-left {
    display: flex;
    align-items: center;
    justify-content: flex-start;
}
.filter-form {
    margin-bottom: 0;
}
.filter-form-left {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 0 16px;
}
:deep(.disabled-row) {
    background-color: #f5f7fa;
    color: #909399;
}
</style>